package com.qyhl.module_practice.activity.detail;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.permissions.RxPermissions;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.module_practice.R;
import com.qyhl.module_practice.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.OtherDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeAcitivityBean;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeIsVolunteerBean;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeVolunteerBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.MJavascriptInterface;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.cache.SpfManager;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;

@Route(path = ARouterPathConstant.PRACTICE_ACT_DETAIL)
public class PracticeActDetailActivity extends BaseActivity implements PracticeActDetailContract.PracticeActDetailView {
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.cover)
    ImageView cover;
    @BindView(R2.id.sub_title)
    TextView subTitle;
    @BindView(R2.id.parameter)
    TextView parameter;
    @BindView(R2.id.web_content)
    WebView webView;
    @BindView(R2.id.act_address)
    TextView actAddress;
    @BindView(R2.id.act_love)
    TextView actLove;
    @BindView(R2.id.end_time)
    TextView endTime;
    @BindView(R2.id.service_time)
    TextView serviceTime;
    @BindView(R2.id.expect_time)
    TextView expectTime;
    @BindView(R2.id.join_num)
    TextView joinNum;
    @BindView(R2.id.tag)
    TextView tag;
    @BindView(R2.id.act_like_btn)
    Button actLikeBtn;
    @BindView(R2.id.sign_public)
    TextView signPublic;
    @BindView(R2.id.sign_volunteer)
    TextView signVolunteer;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.content_layout)
    CardView contentLayout;
    @BindView(R2.id.sign_off_layout)
    LinearLayout signOffLayout;
    @BindView(R2.id.upload_picture)
    TextView uploadPicture;
    @BindView(R2.id.live_cover)
    RoundedImageView liveCover;
    @BindView(R2.id.live_layout)
    CardView liveLayout;
    @BindView(R2.id.street)
    TextView street;
    @BindView(R2.id.person_num)
    TextView personNum;
    @BindView(R2.id.recycle_view)
    RecyclerView recyclerView;
    @BindView(R2.id.person_layout)
    CardView personLayout;

    private String actId;

    private String titleName;

    private String phone = CommonUtils.getInstance().getUserName();

    private PracticeActDetailPresenter mPresenter;

    private PracticeAcitivityBean mData;

    private boolean isApply = false;

    private boolean isFirst;

    private PracticeIsVolunteerBean mBean;

    private List<PracticeVolunteerBean> mDataList = new ArrayList<>();

    private CommonAdapter<PracticeVolunteerBean> commonAdapter;

    private String type;

    private boolean isSign = false;

    private String instId;

    RxPermissions rxPermissions;


    @Override
    protected int getContentView() {
        return R.layout.practice_activity_act_detail;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        actId = getIntent().getStringExtra("id");
        titleName = getIntent().getStringExtra("title");
        type = getIntent().getStringExtra("type");
        instId = getIntent().getStringExtra("instId");
        mPresenter = new PracticeActDetailPresenter(this);
        BusFactory.getBus().register(this);
        rxPermissions = new RxPermissions(this);
        loadMask.setStatus(LoadingLayout.Loading);
        if (StringUtils.isEmpty(titleName)) {
            title.setText("活动详情");
        } else {
            title.setText(titleName);
        }

        recyclerView.setLayoutManager(new GridLayoutManager(this, 5));

        recyclerView.setAdapter(commonAdapter = new CommonAdapter<PracticeVolunteerBean>(this, R.layout.practice_item_act_detail, mDataList) {
            @Override
            protected void convert(ViewHolder holder, PracticeVolunteerBean bean, int position) {
                RoundedImageView cover = holder.getView(R.id.cover);
                Glide.with(PracticeActDetailActivity.this)
                        .load(bean.getLogo())
                        .apply(new RequestOptions().error(R.drawable.comment_head_default).placeholder(R.drawable.comment_head_default))
                        .into(cover);

                holder.setText(R.id.name, bean.getName());
            }
        });

        mPresenter.getDetail(actId, phone);
        if (StringUtils.isNotEmpty(phone)) {
            isFirst = true;
            mPresenter.getIsVolunteer(phone);
        }
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getDetail(actId, phone);
            }
        });
    }


    @OnClick({R2.id.back_btn, R2.id.share_btn, R2.id.act_like_btn, R2.id.sign_public, R2.id.sign_volunteer, R2.id.upload_picture, R2.id.comment, R2.id.cover_layout, R2.id.sign_enter_btn})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.back_btn) {
            finish();
        } else if (id == R.id.share_btn) {
            MPermissionUtils.requestPermissionsResult(PracticeActDetailActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
                @Override
                public void onPermissionGranted() {
                    if (mData != null) {
                        MShareBoard shareBoard = new MShareBoard(PracticeActDetailActivity.this, actId, mData.getName(), mData.getLogo(), "", CommonUtils.getInstance().getBannerId(), 26);
                        shareBoard.showPopupWindow();
                    }
                }

                @Override
                public void onPermissionDenied() {
                    MPermissionUtils.showTipsDialog(PracticeActDetailActivity.this);
                }
            });
        } else if (id == R.id.act_like_btn) {
            if (StringUtils.isEmpty(phone)) {
                RouterManager.routerLogin(PracticeActDetailActivity.this, 0);
                Toasty.normal(PracticeActDetailActivity.this, "尚未登录或登录已失效！", Toast.LENGTH_SHORT).show();
            } else {
                mPresenter.doPraise(actId, phone);
            }
        } else if (id == R.id.sign_public) {

            CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                @Override
                public void login(boolean isLogin) {
                    if (isLogin) {
                        isFirst = true;
                        String username = CommonUtils.getInstance().getUserName();
                        mPresenter.getIsVolunteer(username);
                    } else {
                        Toasty.normal(PracticeActDetailActivity.this, "尚未登录或登录已失效！").show();
                        RouterManager.routerLogin(PracticeActDetailActivity.this, 0);
                    }
                }

                @Override
                public void error(String s) {

                }
            });

        } else if (id == R.id.sign_volunteer) {
            if (mData.getStatus().equals("NOT_BEGIN")) {
                showToast("报名活动将于" + mData.getStartTime() + "开始，敬请期待！", 4);
            } else {
                CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                    @Override
                    public void login(boolean isLogin) {
                        if (isLogin) {
                            String userName = CommonUtils.getInstance().getUserName();
                            mPresenter.getIsVolunteer(userName);
                        } else {
                            Toasty.normal(PracticeActDetailActivity.this, "尚未登录或登录已失效！").show();
                            RouterManager.routerLogin(PracticeActDetailActivity.this, 0);
                        }
                    }

                    @Override
                    public void error(String s) {

                    }
                });
            }
        } else if (id == R.id.upload_picture) {

            CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                @Override
                public void login(boolean isLogin) {
                    if (isLogin) {
                        isApply = true;
                        String userName = CommonUtils.getInstance().getUserName();
                        mPresenter.getIsVolunteer(userName);
                    } else {
                        RouterManager.routerLogin(PracticeActDetailActivity.this, 0);
                    }
                }

                @Override
                public void error(String s) {

                }
            });

        } else if (id == R.id.comment) {

            Bundle bundle = new Bundle();
            bundle.putString("id", actId);
            RouterManager.router(ARouterPathConstant.PRACTICE_COMMENT, bundle);

        } else if (id == R.id.cover_layout) {
        } else if (id == R.id.sign_enter_btn) {

            CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                @SuppressLint("CheckResult")
                @Override
                public void login(boolean isLogin) {
                    if (isLogin) {
                        rxPermissions
                                .request(Manifest.permission.ACCESS_FINE_LOCATION)
                                .subscribe(granted -> {
                                    if (granted) {
                                        if (mData.getIsSign() == 1) {
                                            if (DateUtils.isMiddleOfHourTime(mData.getRegistrationStart(), mData.getRegistrationDeadline())) {
                                                if (mData.getSigninType() == 0) {
                                                    Bundle bundle = new Bundle();
                                                    bundle.putSerializable("bean", mData);
                                                    RouterManager.router(ARouterPathConstant.PRACTICE_SIGN_HOME, bundle);

                                                } else if (mData.getSigninType() == 1 || mData.getSigninType() == 2) {

                                                    Bundle bundle = new Bundle();
                                                    bundle.putString("volId", mData.getVol().getId() + "");
                                                    bundle.putBoolean("isHome", false);
                                                    RouterManager.router(ARouterPathConstant.PRACTICE_QR_CODE, bundle);

                                                } else {
                                                    rxPermissions.request(Manifest.permission.CAMERA)
                                                            .subscribe(granted2 -> {
                                                                if (granted2) {
                                                                    RouterManager.router(ARouterPathConstant.PRACTICE_SCAN);
                                                                }
                                                            });
                                                }
                                            } else {
                                                showToast("服务尚未开始或已经截止！", 4);
                                            }
                                        } else {
                                            showToast("您尚未报名该活动！", 4);
                                        }
                                    } else {
                                        // Oups permission denied
                                    }
                                });
                    } else {
                        Toasty.normal(PracticeActDetailActivity.this, "尚未登录或登录已失效！").show();
                        RouterManager.routerLogin(PracticeActDetailActivity.this, 0);
                    }
                }

                @Override
                public void error(String s) {

                }
            });

        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setDetail(PracticeAcitivityBean bean) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        mData = bean;
        if (isSign) {
            BusFactory.getBus().post(new Event.PracticeSignRefresh(mData));
            isSign = false;
        }
        Glide.with(getApplicationContext())
                .load(bean.getLogo())
                .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                .into(cover);

        subTitle.setText(bean.getName());

        if (mData.getSigninType() == 0) {
            parameter.setText("定位签到  " + bean.getHitCount() + "人感兴趣  " + bean.getCommentCount() + "评论");
        } else {
            parameter.setText("扫码签到  " + bean.getHitCount() + "人感兴趣  " + bean.getCommentCount() + "评论");
        }

        if (bean.getTypes() != null && bean.getTypes().size() > 0) {
            tag.setVisibility(View.VISIBLE);
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < bean.getTypes().size(); i++) {
                if (i == 0) {
                    stringBuilder.append(bean.getTypes().get(i).getName());
                } else {
                    stringBuilder.append("、").append(bean.getTypes().get(i).getName());
                }
            }
            tag.setText(stringBuilder.toString());
        } else {
            tag.setVisibility(View.GONE);
        }

        initWebView();
        if (StringUtils.isNotEmpty(bean.getContent())) {
            contentLayout.setVisibility(View.VISIBLE);
            String htmlString = getNewContent(bean.getContent());
            webView.loadDataWithBaseURL(null, htmlString, "text/html", "utf-8", null);
            webView.addJavascriptInterface(new MJavascriptInterface(this, StringUtils.returnImageUrlsFromHtml(htmlString)), "imagelistener");
            webView.setWebViewClient(new MyWebViewClient());
        } else {
            contentLayout.setVisibility(View.GONE);
        }

        actAddress.setText("地址：" + bean.getAddress());

        actLove.setText("爱心分数：" + bean.getScore() + "分");

        endTime.setText("招募截止：" + DateUtils.practiceSignFormat(bean.getEndTime()));

        serviceTime.setText("服务时间：" + DateUtils.practiceServiceFormat(StringUtils.isEmpty(bean.getRegistrationStart()) ? "" : bean.getRegistrationStart()) + " -" + DateUtils.practiceServiceFormat(StringUtils.isEmpty(bean.getRegistrationDeadline()) ? "" : bean.getRegistrationDeadline()));

        if(bean.getActSignType()==1){
            expectTime.setVisibility(View.GONE);
        }else{
            expectTime.setVisibility(View.VISIBLE);
            expectTime.setText("预计服务时长：" + bean.getServiceTime() + "小时");
        }


        joinNum.setText(bean.getVolunteerNum() + "/" + bean.getQuantityDemanded());

        if (StringUtils.isNotEmpty(type) && "1".equals(type)) {
            street.setText("爱心对接：" + bean.getSource());
        } else {
            street.setText("主办单位：" + bean.getSource());
        }

        if (bean.getQuantityDemanded() == 0) {
            joinNum.setText(bean.getVolunteerNum() + "/不限");
        } else {
            joinNum.setText(bean.getVolunteerNum() + "/" + bean.getQuantityDemanded());
        }


        if (bean.getVolunteers() != null && bean.getVolunteers().size() > 0) {
            personLayout.setVisibility(View.VISIBLE);
            personNum.setText("已报名（" + bean.getVolunteerNum() + "人）");
            mDataList.clear();
            mDataList.addAll(bean.getVolunteers());
            commonAdapter.notifyDataSetChanged();
        } else {
            personLayout.setVisibility(View.GONE);
        }

        switch (bean.getStatus()) {
            case "BEGINNING":
                signOffLayout.setVisibility(View.GONE);
                uploadPicture.setVisibility(View.VISIBLE);
                uploadPicture.setEnabled(false);
                uploadPicture.setText("已开始");
                break;
            case "RECRUIT":
                joinNum.setTextColor(getResources().getColor(R.color.global_base));
                int limit;
                if (bean.getQuantityDemanded() == 0) {
                    limit = 1000000000;
                } else {
                    limit = bean.getQuantityDemanded();
                }

                if (bean.getVolunteerNum() >= limit) {//报名已满
                    signVolunteer.setText("报名已满");
                    signPublic.setEnabled(false);
                    signVolunteer.setEnabled(false);
                    if (bean.getIsSign() == 1) {
                        signOffLayout.setVisibility(View.GONE);
                        uploadPicture.setVisibility(View.VISIBLE);
                        if (bean.getIsCheck() == 0) {
                            uploadPicture.setEnabled(true);
                        } else {
                            uploadPicture.setEnabled(false);
                        }
                    } else if (bean.getIsSign() == 2) {
                        signOffLayout.setVisibility(View.VISIBLE);
                        uploadPicture.setVisibility(View.GONE);
                        signPublic.setText("已报名");
                    } else {
                        signOffLayout.setVisibility(View.VISIBLE);
                        uploadPicture.setVisibility(View.GONE);
                        signPublic.setEnabled(true);
                    }
                } else if (bean.getIsSign() == 1) {//志愿者报名
                    signOffLayout.setVisibility(View.GONE);
                    uploadPicture.setVisibility(View.VISIBLE);
                    uploadPicture.setText("上传活动照片");
                    signPublic.setText("已报名");
                    signVolunteer.setText("已报名");
                    signPublic.setEnabled(false);
                    signVolunteer.setEnabled(false);
                    if (bean.getIsCheck() == 0) {
                        uploadPicture.setEnabled(true);
                    } else {
                        uploadPicture.setEnabled(false);
                    }
                } else if (bean.getIsSign() == 2) {//群众报名
                    signOffLayout.setVisibility(View.GONE);
                    uploadPicture.setVisibility(View.VISIBLE);
                    signPublic.setText("已报名");
                    signVolunteer.setText("已报名");
                    uploadPicture.setText("上传活动照片");
                    signPublic.setEnabled(false);
                    signVolunteer.setEnabled(false);
                    uploadPicture.setEnabled(false);
                } else {//尚未报名
                    signOffLayout.setVisibility(View.VISIBLE);
                    uploadPicture.setVisibility(View.GONE);
                    signPublic.setEnabled(true);
                    signVolunteer.setEnabled(true);
                }
                break;
            case "END":
                joinNum.setTextColor(getResources().getColor(R.color.practice_normal_color));
                if (bean.getIsSign() == 1) {
                    uploadPicture.setText("上传活动照片");
                    signOffLayout.setVisibility(View.GONE);
                    uploadPicture.setVisibility(View.VISIBLE);
                    if (bean.getIsCheck() == 0) {
                        uploadPicture.setEnabled(true);
                    } else {
                        uploadPicture.setEnabled(false);
                    }
                } else if (bean.getIsSign() == 2) {
                    uploadPicture.setText("上传活动照片");
                    signOffLayout.setVisibility(View.GONE);
                    uploadPicture.setVisibility(View.VISIBLE);
                    uploadPicture.setEnabled(false);
                } else {
                    signOffLayout.setVisibility(View.GONE);
                    uploadPicture.setVisibility(View.VISIBLE);
                    uploadPicture.setEnabled(false);
                    uploadPicture.setText("服务已结束");
                }
                break;
            case "SERVICE":
                if (bean.getIsSign() == 1) {
                    uploadPicture.setText("上传活动照片");
                    signOffLayout.setVisibility(View.GONE);
                    uploadPicture.setVisibility(View.VISIBLE);
                    if (bean.getIsCheck() == 0) {
                        uploadPicture.setEnabled(true);
                    } else {
                        uploadPicture.setEnabled(false);
                    }
                } else if (bean.getIsSign() == 2) {
                    uploadPicture.setText("上传活动照片");
                    signOffLayout.setVisibility(View.GONE);
                    uploadPicture.setVisibility(View.VISIBLE);
                    uploadPicture.setEnabled(false);
                } else {
                    signOffLayout.setVisibility(View.VISIBLE);
                    uploadPicture.setVisibility(View.GONE);
                    signPublic.setText("招募已截止");
                    signVolunteer.setText("招募已截止");
                    signPublic.setEnabled(false);
                    signVolunteer.setEnabled(false);
                }
                break;
            default:
                joinNum.setTextColor(getResources().getColor(R.color.practice_normal_color));
                signOffLayout.setVisibility(View.VISIBLE);
                uploadPicture.setVisibility(View.GONE);
                signPublic.setEnabled(true);
                signVolunteer.setEnabled(true);
                break;
        }

        if (bean.getIsLike() == 0) {
            actLikeBtn.setEnabled(true);
        } else {
            actLikeBtn.setEnabled(false);
        }

        actLikeBtn.setText(bean.getFabulous() + "人喜欢");
    }

    @Override
    public void getDetailError(String msg) {
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~");
        if (!NetUtil.isNetworkAvalible(this)) {
            loadMask.setErrorImage(R.drawable.error_network);
            loadMask.setErrorText("网络异常，请检查您的网络！");
        } else if (msg.contains("暂无")) {
            loadMask.setErrorImage(R.drawable.empty_content);
            loadMask.setErrorText(msg);
        } else {
            loadMask.setErrorImage(R.drawable.error_content);
            loadMask.setErrorText(msg);
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void praiseSuccess(int num) {
        actLikeBtn.setEnabled(false);
        actLikeBtn.setText(num + "人喜欢");
    }

    @Override
    public void praiseError(String msg) {
        showToast(msg, 4);
    }

    @Override
    public void setIsVolunteer(PracticeIsVolunteerBean bean) {
        mBean = bean;
        if (isFirst) {
            isFirst = false;
//            switch (mBean.getStatus()) {
//                case "NOT_VERIFY":
//                    showToast("您的志愿者资格审核中！", 4);
//                    break;
//                case "PASS":
//                    showToast("您已经是志愿者！", 4);
//                    break;
//                default:
//                    Router.build("practice_volunteer_sign")
//                            .with("id", actId)
//                            .with("isVolunteer", true)
//                            .go(PracticeActDetailActivity.this);
//                    break;
//            }
            return;
        }

        if (isApply) {
            isApply = false;
            String userName = CommonUtils.getInstance().getUserName();

            Bundle bundle = new Bundle();
            bundle.putString("userName", userName);
            bundle.putString("id", actId);
            bundle.putString("volId", bean.getVolId() + "");
            RouterManager.router(ARouterPathConstant.PRACTICE_APPLY, bundle);
        } else {
            if (bean.getVolId() == 0) {//非志愿者
                showToast("请先注册成为志愿者！", 4);
                Bundle bundle = new Bundle();
                bundle.putBoolean("isVolunteer", true);
                bundle.putString("instId", instId);
                RouterManager.router(ARouterPathConstant.PRACTICE_VOLUNTEER_SIGN, bundle);

            } else {
                switch (bean.getStatus()) {
                    case "PASS":
                        new OtherDialog.Builder(PracticeActDetailActivity.this)
                                .setContentView(R.layout.practice_act_sign_dialog)
                                .setDismissButton(R.id.negative_btn)
                                .setOnClickListener(R.id.positive_btn, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        mPresenter.volunteerSign(actId, mBean.getVolId() + "");
                                    }
                                }).show();

                        break;
                    case "NOT_VERIFY":
                        showToast("志愿者资格审核中", 4);
                        break;
                    case "NOT_PASS":
                    case "DEL": {
                        showToast("请先注册成为志愿者！", 4);
                        Bundle bundle = new Bundle();
                        bundle.putBoolean("isVolunteer", true);
                        bundle.putString("instId", instId);
                        RouterManager.router(ARouterPathConstant.PRACTICE_VOLUNTEER_SIGN);
                    }

                    break;
                    default:
                        break;
                }
            }
        }

    }

    @Override
    public void signResult(boolean isSuccess) {
        if (isSuccess) {
            showToast("报名成功！", 4);
            mPresenter.getDetail(actId, phone);
        } else {
            showToast("报名失败，请稍后再试！", 4);
        }
    }

    /**
     * eventBus 接收器
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.LoginMessage event) {
        if (event != null) {
            if (event.isLogin()) {//登录
                phone = CommonUtils.getInstance().getUserName();
            } else {
                phone = "";
            }
            mPresenter.getDetail(actId, phone);
            isFirst = true;
            mPresenter.getIsVolunteer(phone);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(Event.PracticeActRefresh event) {
        if (event != null) {
            if (event.getType() == 1) {
                isSign = true;
            }
            mPresenter.getDetail(actId, phone);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BusFactory.getBus().unregister(this);
    }


    //webview中的图片自适应大小
    private String getNewContent(String htmltext) {
        Document doc = Jsoup.parse(htmltext);
        Elements elements = doc.getElementsByTag("img");
        for (Element element : elements) {
            element.attr("style", "max-width:100% !important;max-height:auto !important");
        }

        Elements elements1 = doc.getElementsByTag("video");
        for (Element element : elements1) {
            element.attr("width", "100%").attr("height", "auto");
        }

        doc.select("div.titleDivs").remove();

        Log.i("VACK", doc.toString());
        return doc.toString();
    }


    //Web视图
    class MyWebViewClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            webView.getSettings().setBlockNetworkImage(true);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("http:") || url.startsWith("https:")) {
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return false;
            }

            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            /*
             * 非wifi下不加载图片
             */
            if (NetUtil.isWifi(PracticeActDetailActivity.this)) {
                webView.getSettings().setBlockNetworkImage(false);
            } else {
                if (SpfManager.getInstance(PracticeActDetailActivity.this).getBoolean("noPicture", false)) {
                    webView.getSettings().setBlockNetworkImage(true);
                } else {
                    webView.getSettings().setBlockNetworkImage(false);
                }
            }
            //这个是一定要加上那个的,配合scrollView和WebView的height=wrap_content属性使用
            int w = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
            int h = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
            //重新测量
            webView.measure(w, h);
        }

    }

    //初始化webview
    private void initWebView() {
        webView.getSettings().setJavaScriptEnabled(false);
        webView.getSettings().setDefaultTextEncodingName("utf-8");
        webView.getSettings().setUseWideViewPort(false);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        setFontSize(SpfManager.getInstance(this).getInt("fontSize", 2));
        webView.getSettings().setBlockNetworkImage(true);
    }

    /*
     * 设置webview字体大小
     */
    private void setFontSize(int position) {
        switch (position) {
            case 0:
                webView.getSettings().setTextZoom(50);
                break;
            case 1:
                webView.getSettings().setTextZoom(75);
                break;
            case 2:
                webView.getSettings().setTextZoom(100);
                break;
            case 3:
                webView.getSettings().setTextZoom(150);
                break;
            case 4:
                webView.getSettings().setTextZoom(200);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webView != null && webView.canGoBack()) {
                webView.goBack();
            } else {
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        ActionLogUtils.getInstance().onResume(this, ActionConstant.PRACTICE_ACT_DETAIL);
    }

    @Override
    protected void onPause() {
        super.onPause();
        ActionLogUtils.getInstance().onPause(this, ActionConstant.PRACTICE_ACT_DETAIL);
    }

}
